<?php
/**
 * 
 * 好友关系静态类
 * @author will
 *
 */
class Friend {
	/**
	 * 是否是好友关系
	 * @param <int> $uin
	 * @param <int> $to_uin
	 */
	static public function isFriend($uin , $to_uin) {
		$list = self::get($uin);
		$result = array_search($to_uin , $list);
		return $result === false ? false : true;
	}
	
	/**
	 * 从cache中获取数据，如果没有则去数据库取一下
	 * @param <int> $uin
	 * @param <boolean> $refresh_cache
	 */
	static public function get($uin , $refresh_cache = true) {
		$Db = loadDB();
		
		$list = $Db->getOne("SELECT `list` FROM `friend_cache` WHERE `uin` = {$uin}" , 'list');
		if($list === false && $refresh_cache) {
			$list = self::refreshCache($uin);
		}
		
		if(!empty($list)) {
			if( !is_array($list)) {
				$list = trim($list);
				$list = explode("\n" , $list);
			}
		} else {
			$list = array();
		}
		
		return $list;
	}
	
	/**
	 * 刷新好友缓存
	 * @param <int> $uin
	 */
	static public function refreshCache($uin) {
		$Db = loadDB();
		
		// 读真实数据
		$result = $Db->getAll("SELECT `uin` , `to_uin` FROM `friend` WHERE `uin` = {$uin} OR `to_uin` = {$uin}");
		$result = empty($result) ? array() : $result;
		
		$list = array();
		foreach($result as $row) {
			$list[] = $row['uin'] == $uin ? $row['to_uin'] : $row['uin'];
		}
		
		// 写回cache
		$insert_data = array('uin' => $uin , 'list' => implode("\n" , $list) , 'time' => time());
		$Db->doInsert('friend_cache' , $insert_data);
		
		return $list;
	}
	
	/**
	 * 加为好友关系
	 * @param <int> $uin
	 * @param <int> $to_uin
	 */
	static public function add($uin , $to_uin) {
		// 保证小的uin在前，大的在后
		if($uin > $to_uin) {
			$tmp = $to_uin;
			$to_uin = $uin;
			$uin = $tmp;
		}
		
		$Db = loadDB();
		// 判断双方上限
		// ..todo
		
		$time = time();
		// 写入数据
		$insert_data = array(
			'uin' => $uin,
			'to_uin' => $to_uin,
			'time' => $time,
		);
		$success = $Db->doInsert('friend' , $insert_data);
		
		// 删除 cache
		$Db->query("DELETE FROM `friend_cache` WHERE `uin` IN ({$uin} , {$to_uin})");
		
		return $success ? 0 : 101;
	}
	
	/**
	 * 删除好友关系
	 * @param <int> $uin
	 * @param <int> $to_uin
	 */
	static public function delete($uin , $to_uin) {
		// 保证小的uin在前，大的在后
		if($uin > $to_uin) {
			$tmp = $to_uin;
			$to_uin = $uin;
			$uin = $tmp;
		}
		
		$Db = loadDB();
		
		// 写入数据
		$success = $Db->query("DELETE FROM `friend` WHERE `uin` = {$uin} AND `to_uin` = {$to_uin}");
		
		// 删除 cache
		$Db->query("DELETE FROM `friend_cache` WHERE `uin` IN ({$uin} , {$to_uin})");
		
		return $success ? 0 : 102;
	}
}


# end of script
